document.oncontextmenu=new Function('event.returnValue=false;');
document.onselectstart=new Function('event.returnValue=false;');
/* main javascript fo wephoto */

var gallery = new Gallery();
var timer = null;
var eventId = location.href.match(/\/event\/([0-9]+)/)[1];
var startTime = 0;
var config = {
	requestInterval: 4000,
	MsgStayTime: 2000,
	maxSelectedPhotoNumber: 6,
	printPending: false,
	sendEmailPending: false
};
var qrcode = new QRCode(document.getElement('.qrcode'), {
		width : 165, 
		height : 165,
		typeNumber : 4,
		colorDark : "#000000",
		colorLight : "#ffffff"
});

qrcode.makeCode(location.href);	
/**
 * @function clean up email input filed and hide the qrcode
 *
 */
var emailClean = function(){
	var email = document.getElement('.email');
	if(email){
		email.set('value', '');
		document.getElement('.qrcode').setStyle('display', 'none');
	}
}
/**
 * event handle when send email button has been click
 * 
 */
var sendEmail = document.getElement('.sendEmail');
if(sendEmail){
	sendEmail.addEvent('click', function(e){
		var ele = $(this);
		var coor = ele.getElement('!~').getOffsets();
		if(!config.sendEmailPending){
			config.sendEmailPending = true;
			var emailAdress = document.getElement('.email').get('value').trim();
			if(!emailAdress || !Utils.isEmail(emailAdress)){
				messager('Please input a valid email.', 'wanning', {
					x: coor.x + 5,
					y: coor.y - ele.getSize().y + 30
				});
				config.sendEmailPending = false;
			}else{
				Sync.postEmail(uriMap, {email: emailAdress})
					.then(function(res){
						messager('Your email has been sent.', 'success', {
							x: coor.x + 5,
							y: coor.y - ele.getSize().y + 30
						});
						ele.addClass('sent');
						setTimeout(function(){
							document.getElement('.email').set('value', '');
							config.sendEmailPending = false;
							ele.removeClass('sent');
						}, 1500);
					})
					.catch(function(err){
						if(err){
							console.log(err);
						}
					});

			}
		}else{
		}
	});
}
/**
 * event handle when email input blur or focus
 *
 * when blur check the valid form of the email if valid show qrcode
 * when focus it reset the send email flag to false
 */
var emailInput = document.getElement('.email');
if(emailInput){
	emailInput.addEvents({'blur': function(e){
		var value = $(this).get('value').trim();
		if(Utils.isEmail(value)){
			var qr = document.getElement('.qrcode');
			if(qr.getStyle('display') == 'none'){
				qr.setStyle('display','block');
			}
		}
	},'focus': function(e){
		config.sendEmailPending = false;
	}});
}
/**
 * event handle when click on the language switch button
 * 
 * currently support Chinese and English
 */
document.getElements('.sl')
	.addEvent('click', function(e){
		var ele = $(this);
		var lang = ele.get('data-lang');
		$$('.sl').removeClass('active');
		if(lang === 'en'){
			$$('.lang_en').setStyle('display','inline');
			$$('.lang_cn').setStyle('display', 'none');
		}else{
			$$('.lang_cn').setStyle('display','inline');
			$$('.lang_en').setStyle('display', 'none');
		}
		ele.addClass('active');
	});
/**
* event handle when click the print button
*
* use api insert pring data
*/
document.getElement('.btn-print')
	.addEvent('click', function(e){
		var ele = $(this);
		var coor = ele.getOffsets();
		if(!config.printPending){
			config.printPending = true;
			var selectedPhotos = document.getElements('.vertical-nav li');
			var printItems = [];
			selectedPhotos.forEach(function(photo){
				printItems.push({
					photoId: photo.get('photo_id')
				});
			});
			Sync.postPrint(eventId, printItems)
				.then(function(res){
					messager('Your photos has been printed.', 'success', {
						x: coor.x,
						y: coor.y - ele.getSize().y + 10
					});
				})
				.catch(function(err){
					console.log(err);
				})
		}else{
			messager('Your photos has been printed.', 'success', {
				x: coor.x,
				y: coor.y - ele.getSize().y + 10
			});
		}
	});
/**
 * event handle when click the back button
 *
 * go to stage 1 from stage 2
 * it will reset prnt flag and send email flag which preventing multi click
 * on button of print or send email 
 * it will clear the photos on the collection.
 */
document.getElement('.btn-back')
	.addEvent("click", function(){
		document.getElement('.stage2').setStyle('display', 'none');
		document.getElement('.stage1').setStyle('display', 'block');
		config.printPending = false;
		config.sendEmailPending = false;
		//emailClean();
	});
document.getElement('.btn-finish')
	.addEvent("click", function(){
		gallery.photos.forEach(function(photo){
			photo.isSelected = false;
		});
		document.getElements('.gallery-photo').forEach(function(photo){
			photo.removeClass('selected');
		});
		document.getElement('.collector-collection ul').empty();
		config.printPending = false;
		config.sendEmailPending = false;
		document.getElement('.stage2').setStyle('display', 'none');
		document.getElement('.stage1').setStyle('display', 'block');
		emailClean();
	});
/*
document.getElement('.show-window-delete')
	.addEvent('click', function(){
		var selectedPhotos = docuemnt.getElements('.collector-collection li');
		if(selectedPhotos.length > 0){
			var photo_id = $('main-show').get('photo_id');
			var photoToDelete = selectedPhotos.find(function(photo){
				return photo.photo_id === photo_id;
			});

		}
	});
*/
/**
 * event handle for switch photos on the main view
 * 
 * It's on stage 2, several photos been selected, but on the main view
 * it can only show one photo at a time, so when user click on the 
 * different photo on the vertical nav, it will show that photo on the 
 * main view.
 */

document.getElement('.vertical-nav')
	.addEvent('click:relay(li)', function(e, ele){
		var photo_id = ele.get('photo_id');
		var src = ele.getElement('img').get('src');
		$('main-show').set({
			photo_id: photo_id,
			src: src
		});
	});
/**
 * event handle when click the next button
 *
 *	if there is no elememt in the collection it won't response
 *  it will send the ids of photo in the collection to server to get
 * a share uri map, which been used to generate qrcode, for there photos
 * and change to stage 2
 */
document.getElement('.collector-next')
	.addEvent('click', function(){
		var selectedPhotos = document.getElements('.collector-collection li');
		if(selectedPhotos.length > 0){
			var stage2 = document.getElement('.stage2');
			stage2.getElements('.vertical-nav li').forEach(function(ele){
				ele.destroy();
			});
			stage2.getElement('#main-show')
				.set({
					photo_id: selectedPhotos[0].get('photo_id'),
					src: selectedPhotos[0].getElement('img').get('src')
				});
			var html = '';
			var shareContent = [];
			selectedPhotos.forEach(function(photo){
				var src = photo.getElement('img').get('src');
				var photoId = photo.get('photo_id');
				html += '<li photo_id="' + photoId + '"><img src="' + src + '"></li>';
				shareContent.push(photoId);
			});
			stage2.getElement('.vertical-nav ul')
				.appendHTML(html);

			Sync.postShare(eventId, shareContent)
				.then(function(res){
					var uriMap = window.uriMap = res.uri_map;
					var sharePage = location.protocol + "//" + location.host + "/share/" + uriMap;
					qrcode.makeCode(sharePage);					
					stage2.setStyle('display','block');
					document.getElement('.stage1').setStyle('display','none');
				})
				.catch(function(err){
					console.log(err);
				});

		}
	});
/**
 * event proxy for cancel selected photos
 *
 * self destroy, the same photo id in gallery switch isSelected to false,
 * the same photo id in gallery view remove class "selected"
 */
document.getElement('.collector-collection')
	.addEvent("click:relay(li)", function(e, ele){
		var photo_id = ele.get('photo_id');
		gallery.photos.forEach(function(photo){
			if(photo.photo_id == photo_id){
				photo.isSelected = false;
			}
		});
		gallery.$el.getElements('.gallery-photo')
					.forEach(function(photo){
						if(photo.get('photo_id') == photo_id){
							photo.removeClass('selected');
						}
					});
		ele.destroy();
	});
/**
 * event proxy for gallery view elements, click, it will be selected
 * click if it has been selected, it will been cancel.
 * if there already reach the number limit in collection, it will auto
 * remove the first element in the collection and add the new selected 
 * one
 */
gallery.$el.addEvent("click:relay(li)", function(e, ele){
	var photo_id = ele.get('photo_id');
	var selectedPhotos = document.getElements('.collector-collection li');
	if(ele.hasClass('selected')){
		ele.removeClass('selected');
		selectedPhotos.forEach(function(photo){
			if(photo.get('photo_id') == photo_id){
				photo.destroy();
			}
		});
		gallery.photos.forEach(function(photo){
			if(photo.photo_id == photo_id){
				photo.isSelected = false;
			}
		});
	}else{
		if(selectedPhotos.length === config.maxSelectedPhotoNumber){
			var canceledId = selectedPhotos[0].get('photo_id');
			var eleInViewport = gallery.$el.getElement('[photo_id=' + canceledId + ']')
			if(eleInViewport){
				eleInViewport.removeClass('selected');
			}
			gallery.photos.forEach(function(photo){
				if(photo.photo_id == canceledId){
					photo.isSelected = false;
				}
			});
			selectedPhotos[0].destroy();
		}
		ele.addClass('selected');
		var html = '<li photo_id="' + photo_id + '" style="opacity:0" ><img src="' + ele.getElement('img').get('src') + '"></li>';
		document.getElement('.collector-collection ul').appendHTML(html);
		gallery.photos.forEach(function(photo){
			if(photo.photo_id == photo_id){
				photo.isSelected = true;
			}
		});
		var tn = document.getElement('.collector-collection [photo_id='+photo_id+'] > img');
		var eleCoor = ele.getElement('img').getOffsets();
		var tnCoor = tn.getOffsets();
		var aniEle = new Element('img', {
			src: ele.getElement('img').get('src'),
			styles: {
				width: ele.getElement('img').getStyle('width'),
				height: ele.getElement('img').getStyle('height'),
				position: 'absolute',
				left: eleCoor.x + "px",
				top: eleCoor.y + "px"
			}
		})
		var handleComplete = function(){
			aniEle.destroy();
			tn.getParent('li').setStyle('opacity', 1);
		};
		document.body.grab(aniEle);
		TweenLite.to(aniEle, .5, {left:tnCoor.x, top:tnCoor.y, width:tn.getStyle('width'), height: tn.getStyle('height'), onComplete: handleComplete});
	}

	
})

function messager(message, type, position){
	var msg = new Element('div', {
		class:'message ' + type,
		html: message,
		styles: {
			left: position.x + "px",
			top: position.y + "px"
		}
	});
	document.body.grab(msg);
	setTimeout(function(){
		msg.destroy();
	}, config.MsgStayTime);
}

callPhotos();
function callPhotos(){
	timer = setTimeout(callPhotos, config.requestInterval);
	Sync.getPhotolist(eventId, startTime)
		.then(function(results){
			if(results.length > 0){
				startTime = results.getLast().timestamp;
				gallery.introduce(results);
			}
		})
		.catch(function(err){
			console.log(err);
		});
}